<?php

namespace App\Http\Controllers\Back;

use App\Http\Controllers\Controller;
use App\Model\ArticleCategories;
use App\Model\Articles;


use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;


class ArticleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {

        $query = Articles::orderBy('created_at','asc')->select('id', 'title', 'sort', 'article_category_id', 'cover','pageviews', 'created_at', 'updated_at','actual_pageviews');

        if ($article_category_id =  $request->query('article_category_id')){
            $query = $query->where('article_category_id',$article_category_id);
        }

//        if ($request->query('article_category'))
        if ($title  = $request->query('title')){

            $query = $query->where('title', 'like',"%$title%");
        }

        if ($start_create = $request->query('start_create_time')){
            $query = $query->where('created_at',  '>=', $start_create);
        }

        if ($end_create = $request->query('end_time')){
            $query = $query->where('created_at',  '<=', $end_create);
        }

        if ($start_update = $request->query('start_update_time')){
            $query = $query->where('created_at',  '>=', $start_update);
        }

        if ($end_update = $request->query('end_update_time')){
            $query = $query->where('created_at',  '>=', $end_update);
        }
        $per_page = $request->query('per_page', 20);

        $articleItems = $query->paginate($per_page);


        $categoryies = ArticleCategories::orderBy('sort', 'asc')->pluck('title','id');
        $data = [];
        foreach ($articleItems as $articleItem){
            $categoryies_id =    $articleItem['article_category_id'];
            $item = [
                'uuid' => $articleItem['id'],
                'title' => $articleItem['title'],
//                'content' => $articleItem['content'],
                'cover' => $articleItem['cover'],
                'article_category_name' =>   isset($categoryies[$categoryies_id]) ? $categoryies[$categoryies_id] : '',
                'sort'  => $articleItem['sort'],
                'pageviews'=> $articleItem['pageviews'],
                'actual_pageviews' => $articleItem['actual_pageviews'],
                'created_at'    => $articleItem['created_at']->format('Y-m-d H:i:s'),
                'updated_at'    => $articleItem['updated_at']->format('Y-m-d H:i:s'),
            ];
            array_push($data,$item);
        }


        $articleCategories = ArticleCategories::orderBy('sort','asc')->get();

        return $this->renderJson([
            'list' => $data,
            'articleCategories' => $articleCategories,
            'pagination' => [
                'current' => $articleItems->currentPage(),
                'per_page' => $per_page,
                'total' => (int)ceil($articleItems->total() / $per_page),
                'count' => $articleItems->total()
            ]
        ]);

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

        $this->validate($request,[
            'title' => 'required',
            'content' => 'required',
            'cover' => 'required',
            'article_category_id' => 'required',
            'creator' => 'required',
            'pageviews' => 'required',
        ],[
            'required' => ':attribute不能为空',
        ],[
            'title' => '标题',
            'content' => '内容',
            'cover' => '封面地址',
            'article_category_id' => '分类不能为空',
            'creator' => '操作人',
            'required' => '虚拟浏览量'
        ]);
        $article = new Articles();

        if (!$article->add($request)){
            return $this->error('添加失败');
        }
        Cache::flush();
        return $this->success();

    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $articleCategory = Articles::where('id', $id)->firstOrFail();
        $articleCategory['content'] = str_replace('&nbsp;',' ',$articleCategory['content']);
        return $this->renderJson($articleCategory);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {

        $this->validate($request,[
            'title' => 'required',
            'content' => 'required',
            'cover' => 'required',
            'article_category_id' => 'required',
            'creator' => 'required',
            'pageviews' => 'required',
        ],[
            'required' => ':attribute不能为空',
        ],[
            'title' => '标题',
            'content' => '内容',
            'cover' => '封面地址',
            'article_category_id' => '分类不能为空',
            'creator' => '操作人',
            'pageviews' => '虚拟浏览量',
        ]);
        $article = Articles::findOrFail($id);

        if (!$article->add($request)){
            return $this->error('添加失败');
        }
        //清除缓存
        Cache::forget('article-'.$id);
        return $this->success();

    }

    /**
     * Remove the specified resource from storage.
     * @param $id
     * @return \Illuminate\Http\Response
     * @throws \Exception
     */
    public function destroy($id)
    {
        $item = Articles::findOrFail($id);
        $res  =  $item->delete();
        if ($res == true){
            Cache::forget('article-'.$id);
            Cache::forget('articles');
            return $this->success('删除成功！');
        }
        return $this->error('删除失败！');

    }

    public function checkoutCategory(Request $request)
    {
        $id = $request->input('id');
//        var_dump($id);die;
        $article =  Articles::findOrFail($id);

        $article->article_category_id = $request->input('article_category_id');
        Cache::forget('article-'.$id);
        $res =  $article->update();
        if ($res == true){
            return $this->success('删除成功！');
        }
        return $this->error('删除失败！');
    }
}
